package net.godbirds.aps.micros;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.godbirds.domain.mapper.TDefMicrosMapper;
import net.godbirds.domain.mapper.TDefRoleMapper;
import net.godbirds.domain.mapper.TDefRoleMicrosRelaMapper;
import net.godbirds.domain.mapper.TDefUserRoleRelaMapper;
import net.godbirds.domain.model.TDefMicros;
import net.godbirds.domain.model.TDefMicrosExample;
import net.godbirds.domain.model.TDefRoleMicrosRela;
import net.godbirds.domain.model.TDefRoleMicrosRelaExample;
import net.godbirds.domain.model.TDefUser;
import net.godbirds.domain.model.TDefUserRoleRela;
import net.godbirds.domain.model.TDefUserRoleRelaExample;
@Service
public class MicrosService {

	@Autowired
	TDefRoleMapper tDefRoleMapper;
	@Autowired
	TDefUserRoleRelaMapper tDefUserRoleRelaMapper;
	@Autowired
	TDefMicrosMapper tDefMicrosMapper;
	@Autowired
	TDefRoleMicrosRelaMapper tDefRoleMicrosRelaMapper;
	
	/**
	 * 获取用户所对应额服务<br>
	 * 1、根据用户ID获取角色;
	 * 2、根据角色获取能使用（关联的）微服务;
	 * 3、返回微服务;<br>
	 * 备注：此处本可以1各SQL配置到XML即可查询出来，但是想到兼容各种数据库，所以纯java编写，主要参考Mybatis实例的用法
	 * @param tUser
	 * @return
	 */
	public List<TDefMicros> getMicros(TDefUser tUser){
		TDefUserRoleRelaExample example = new TDefUserRoleRelaExample();
		example.createCriteria().andUserIdEqualTo(tUser.getId().intValue());
		List<TDefUserRoleRela> tdurrs =  tDefUserRoleRelaMapper.selectByExample(example);
		//减少后面访问数据库，此处判断无则不用查询
		if(tdurrs == null || tdurrs.size() <= 0) {
			return null;
		}
		List<Integer> rs = new ArrayList<Integer>();
		for(TDefUserRoleRela t: tdurrs) {
			rs.add(t.getRoleId());
		}
		TDefRoleMicrosRelaExample example1 = new TDefRoleMicrosRelaExample();
		example1.createCriteria().andRoleIdIn(rs);
		List<TDefRoleMicrosRela> tdrmrs = tDefRoleMicrosRelaMapper.selectByExample(example1);
		rs.clear();//移除后再用
		//减少后面访问数据库，此处判断无则不用查询
		if(tdrmrs == null || tdrmrs.size() <= 0) {
			return null;
		}
		for(TDefRoleMicrosRela t: tdrmrs) {
			rs.add(t.getMicrosId());
		}
		TDefMicrosExample example2 = new TDefMicrosExample();
		example2.createCriteria().andIdIn(rs);
		return tDefMicrosMapper.selectByExample(example2);
	}
}
